//
//  BaseViewController.swift
//  WeiFinance
//
//  Created by IOS-User on 2017/4/1.
//  Copyright © 2017年 IOS-User. All rights reserved.
//

import UIKit

/**
 * App 视图基类
 */
class BaseViewController: UIViewController,ViewControllerProtocol {
    
    
    //MARK: - proterty
    lazy var navView:UIView? = UIView.init()
    lazy var labPageTitle:YYLabel? = YYLabel.init()
    lazy var btnNavigationBack:UIButton? = UIButton.init(type: .custom)
    
    lazy var x = CGFloat.init(0)
    lazy var y = CGFloat.init(0)
    lazy var w = CGFloat.init(0)
    lazy var h = CGFloat.init(0)
    

    //MARK: - override
    override func loadView() {
        super.loadView()
        
        self.rac_signal(for: #selector(viewDidLoad))?.subscribeNext({[weak self] (_any:Any?) in
            guard let self = self else { return }
            
            self.layoutNavigation()
            self.addSubViews()
            self.bindViewModel()
        })

        self.rac_signal(for: #selector(viewWillAppear(_:)))?.subscribeNext({[weak self] (_any:Any?) in
            guard let self = self else { return }
            
            self.recoverKeyboard()
            self.getNewData()
        })
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

       DispatchQueue.main.async {
           //背景色
           self.view.backgroundColor = K_APP_VIEWCONTROLLER_BACKGROUND_COLOR
           
           //防止顶部空白
           self.automaticallyAdjustsScrollViewInsets = false
       }

    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        //隐藏状态栏
        self.navigationController?.navigationBar.isHidden = true
        self.navigationController?.toolbar.isHidden = true
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    /// 状态栏
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .default
    }
    
    override var prefersStatusBarHidden: Bool{
        return false
    }
    
    deinit {
        print("\(self.className()) 已销毁")
    }
    
    
    //MARK: - RAC
    /** 绑定 */
    func bindViewModel(){}

    /** 添加控件 */
    func addSubViews(){}

    /** 初次获取数据 */
    func getNewData(){}

    /** 设置navation 标题等 */
    func layoutNavigation(){}

    func recoverKeyboard(){}
}


//MARK: -
extension BaseViewController {
    
    /** initNavgationBar 设置导航栏 */
    func initNavgationBar(backgroundColor:UIColor = K_APP_NAVIGATION_BACKGROUND_COLOR,
                          isBottomLine:Bool = true,
                          isShadow:Bool = false,
                          isOffset:CGFloat = 0){
        //导航
        x = 0
        y = 0
        h = K_APP_NAVIGATION_BAR_HEIGHT
        if isOffset > 0 {
           h += isOffset
        }

        navView?.frame = .init(x: x, y: y, width: K_APP_WIDTH, height: h)
        super.view.addSubview(navView!)

        //背景色值
        navView?.backgroundColor = backgroundColor

        //底部线
        if isBottomLine {
            h = 1
            y = (navView?.frame.size.height)! - h
            let tempImg = UIImageView.init(frame: .init(x: 0, y: y, width: K_APP_WIDTH, height: h))
            tempImg.backgroundColor = K_APP_SPLIT_LINE_COLOR
            navView?.addSubview(tempImg)
        }

        //底部阴影
        if isShadow {
            Utils.shareInstance().setViewShadowStyle(uView: self.navView!,
                               shadowRadius: CGFloat.init(4),
                               shadowOffset: CGSize.init(width: 0, height: 0.8))
        }
    }

    
    /** 初始化视图标题 */
    func initViewControllerTitle(strTitle:String,
                                 fontColor:UIColor = K_APP_VIEWCONTROLLER_TITLE_COLOR,
                                 isBold:Bool = true,
                                 fontSize:CGFloat = K_APP_VIEWCONTROLLER_TITLE_FONT){

        if navView == nil {
           self.initNavgationBar()
        }

        w = K_APP_WIDTH - 80
        h = 21
        y = UIDevice.current.isiPhoneX() ? 55.5 : 31.5
        x = (K_APP_WIDTH - w) / 2
        labPageTitle?.frame = .init(x: x, y: y, width: w, height: h)

        labPageTitle?.textAlignment = .center
        labPageTitle?.textColor = fontColor
        //labPageTitle?.adjustsFontSizeToFitWidth = true

        //标题字体
        if !isBold {
            labPageTitle?.font = UIFont.systemFont(ofSize: fontSize)
        }
        else{
            labPageTitle?.font = UIFont.systemFont(ofSize: fontSize, weight: .bold)
        }

        labPageTitle?.text = strTitle
        navView?.addSubview(self.labPageTitle!)
    }


    /** 初始化导航返回 */
    func initNavigationBack(strBackImagName:String = "nav_back_bg_black.png"){

        w = 40
        h = 40
        x = 12
        y = UIDevice.current.isiPhoneX() ? 46 : 22
        btnNavigationBack?.frame = CGRect.init(x: x, y: y, width: w, height: h)

        btnNavigationBack?.addTarget(self, action: #selector(btnNavigationBackAction(sender:)), for: .touchUpInside)
        btnNavigationBack?.setImage(UIImage.init(named: strBackImagName), for: .normal)
        self.view.addSubview(btnNavigationBack!)
    }

    //返回
    @IBAction func btnNavigationBackAction(sender:UIButton?){
        //present 进入
        if super.presentingViewController != nil {
            var _presentingController:UIViewController? = super.presentingViewController
            while(_presentingController != nil && _presentingController?.presentingViewController != nil){
               _presentingController = _presentingController?.presentingViewController
            }
            _presentingController?.dismiss(animated: true, completion: nil)
        }
        //push 进入
        else{
            self.navigationController?.popViewController(animated: true)
        }
    }

    
    /// 网络通知
    /// - Parameter sender: Notification
    @objc private func netWorkNotice(sender:Notification){
        
        let usernfo:[String:AnyObject] = sender.userInfo as! [String : AnyObject]

        //MARK: -- 网络已断开
        if let code = usernfo["code"] as? Int,code == 404 {
            //当前网络不可用
            SVProgressHUD.showInfo(withStatus: "世上最遥远的距离就是没有网")
        }

        //MARK: -- 网络已连接
        else {
           print("网络已连接")
        }
    }
    
    
    /// 去登录
    /// - Parameter fb: (()->(Void))?
    func toLogin(Finish fb:(()->(Void))?){
        
        let vc = LoginViewController.init()
        vc.loginFinishBlock = {
            fb?()
        }
        
        let _window:UIWindow = (UIApplication.shared.keyWindow ?? UIApplication.shared.windows.first)!
        
        _window.rootViewController?.modalTransitionStyle = .flipHorizontal
        UIView.transition(with: _window,
                           duration: 0.9,
                           options: UIView.AnimationOptions.transitionFlipFromRight,
                           animations: {
                            let oldState:Bool = UIView.areAnimationsEnabled
                            UIView.setAnimationsEnabled(false)
                             
                            _window.rootViewController?.dismiss(animated: false, completion: {
                                   print("rootViewController 已移除")
                            })
                            
                            _window.rootViewController?.removeFromParent()
                            _window.rootViewController = nil
                            _window.rootViewController = vc
                            
                            UIView.setAnimationsEnabled(oldState)
        }, completion: { (result:Bool) in
            print("去登录")
        })
    }
}


//MARK: - UIGestureRecognizerDelegate
extension BaseViewController : UIGestureRecognizerDelegate {
    
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {

        let touchClass = NSStringFromClass((touch.view?.classForCoder)!)
        let supClass = NSStringFromClass((touch.view?.superview!.superview?.classForCoder)!)

        if touchClass.hasPrefix("UITableView") || touchClass.hasPrefix("UICollectionView") ||
           supClass.hasPrefix("UITableView") || supClass.hasPrefix("UICollectionView") {
           return false
        }
        return true
    }
    
}

